# coding=utf-8

"""
@author  zhongy
@date    2018-10-17
@desc    数据集controller
"""

from controller.controller_base import *


class DataSetController(ControllerBase):
    def __init__(self):
        super(DataSetController, self).__init__()

    # 添加数据集
    def add(self, data_set_name):
        data_set = DataSet(data_set_name=data_set_name)
        self.db.session.add(data_set)
        self.db.session.commit()
        self.db.session.close()
        return True

    # 查询数据集列表
    def list(self, data_set_name=None, page_index=None, page_size=None):
        data_set_list = self.db.session.query(DataSet). \
            filter(and_(DataSet.data_set_name.like('%' + data_set_name + '%'), DataSet.is_deleted == False))\
            .order_by(DataSet.create_time.desc()).paginate(page_index, page_size)

        pagination = {
            'page_size': page_size,
            'page_index': page_index,
            'total': data_set_list.total,
            'page_count': data_set_list.pages
        }

        if data_set_list.items is not None:
            result = model_serialize(data_set_list.items)
            return result, pagination
        else:
            return [], pagination

    # 查询全部数据集
    def all(self, data_set_name=None):
        data_set_list = self.db.session.query(DataSet). \
            filter(and_(DataSet.data_set_name.like('%' + data_set_name + '%'), DataSet.is_deleted == False)) \
            .order_by(DataSet.create_time.desc()).all()
        if data_set_list is not None:
            return model_serialize(data_set_list)
        else:
            return []

    # 更新数据集
    def update(self, data_set_id, data_set_name=None, is_deleted=None):
        data_set = self.db.session.query(DataSet).get(data_set_id)
        if data_set_name is not None:
            data_set.data_set_name = data_set_name
        if is_deleted is not None:
            data_set.is_deleted = is_deleted
        self.db.session.commit()
        self.db.session.close()
        return True

    # 根据数据集名称查询单个数据集
    def get_by_name(self, data_set_name):
        data_set = self.db.session.query(DataSet).filter(and_(DataSet.is_deleted == False,
                                                              DataSet.data_set_name == data_set_name)).first()
        return data_set


